<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />





  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "0b6e024b"
    });
  daovoice('update');
  </script>














  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python,Python编程快速上手," />










<meta name="keywords" content="Python,Python编程快速上手">
<meta property="og:type" content="article">
<meta property="og:title" content="Python编程快速上手 学习笔记(二) 电话号码和 E-mail 地址提取程序">
<meta property="og:url" content="http://yoursite.com/2018/09/02/python/python_note_2/index.html">
<meta property="og:site_name" content="万般皆下品 唯有读书高">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/9140378-b5624c2f9b81ebb6.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-09-03T13:55:41.385Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python编程快速上手 学习笔记(二) 电话号码和 E-mail 地址提取程序">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/9140378-b5624c2f9b81ebb6.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/09/02/python/python_note_2/"/>





  <title>Python编程快速上手 学习笔记(二) 电话号码和 E-mail 地址提取程序 | 万般皆下品 唯有读书高</title>
  








</head>


   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas>
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script>
   <script type="text/javascript" src="/js/src/fireworks.js"></script>


<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">万般皆下品 唯有读书高</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">小生的学习笔记</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/09/02/python/python_note_2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="HyYyr Wang">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/icon.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="万般皆下品 唯有读书高">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python编程快速上手 学习笔记(二) 电话号码和 E-mail 地址提取程序</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-02T22:18:58+08:00">
                2018-09-02
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Python/" itemprop="url" rel="index">
                    <span itemprop="name">Python</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,703
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  8
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://upload-images.jianshu.io/upload_images/9140378-b5624c2f9b81ebb6.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="12.jpg"></p>
<hr>
<a id="more"></a>
<h1 id="Python编程快速上手-学习笔记-二"><a href="#Python编程快速上手-学习笔记-二" class="headerlink" title="Python编程快速上手 学习笔记(二)"></a>Python编程快速上手 学习笔记(二)</h1><h2 id="先复习一下上一篇文章Python编程快速上手-学习笔记-一-匹配模式与正则表达式-的主要内容"><a href="#先复习一下上一篇文章Python编程快速上手-学习笔记-一-匹配模式与正则表达式-的主要内容" class="headerlink" title="先复习一下上一篇文章Python编程快速上手 学习笔记(一) 匹配模式与正则表达式 的主要内容"></a>先复习一下上一篇文章<a href="https://wanghao15536870732.github.io/2018/09/02/python/python-note-1/" target="_blank" rel="noopener">Python编程快速上手 学习笔记(一) 匹配模式与正则表达式</a> 的主要内容</h2><table>
<thead>
<tr>
<th style="text-align:left">正则表达式符号</th>
<th style="text-align:left">代表的意思</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">？</td>
<td style="text-align:left">匹配零次或一次前面的分组</td>
</tr>
<tr>
<td style="text-align:left">*</td>
<td style="text-align:left">匹配零次或多次前面的分组</td>
</tr>
<tr>
<td style="text-align:left">+</td>
<td style="text-align:left">匹配一次或多次前面的分组</td>
</tr>
<tr>
<td style="text-align:left">{n}</td>
<td style="text-align:left">匹配n次前面的分组</td>
</tr>
<tr>
<td style="text-align:left">{n,}</td>
<td style="text-align:left">匹配n次或更多前面的分组</td>
</tr>
<tr>
<td style="text-align:left">{,m}</td>
<td style="text-align:left">匹配零次到m次前面的分组</td>
</tr>
<tr>
<td style="text-align:left">{n,m}</td>
<td style="text-align:left">匹配至少n次，至多m次前面的分组</td>
</tr>
<tr>
<td style="text-align:left">{n,m}? 、 * ?  、+ ?</td>
<td style="text-align:left">对前面的分组进行非贪心匹配</td>
</tr>
<tr>
<td style="text-align:left">^ spam</td>
<td style="text-align:left">意味着查找的字符串必须以 spam 开头</td>
</tr>
<tr>
<td style="text-align:left">.</td>
<td style="text-align:left">匹配所有字符，换行字符除外</td>
</tr>
<tr>
<td style="text-align:left">\d、\w 和 \s</td>
<td style="text-align:left">分别匹配数字、单词和空格</td>
</tr>
<tr>
<td style="text-align:left">\D、\W 和 \S</td>
<td style="text-align:left">分别匹配数字、单词和空格 除外的所有字符</td>
</tr>
<tr>
<td style="text-align:left">[abc]</td>
<td style="text-align:left">匹配方括号内的任意字符</td>
</tr>
<tr>
<td style="text-align:left">[^abc]</td>
<td style="text-align:left">匹配不在方括号内的任意字符</td>
</tr>
</tbody>
</table>
<h2 id="深入学习正则表达式"><a href="#深入学习正则表达式" class="headerlink" title="深入学习正则表达式"></a>深入学习正则表达式</h2><h3 id="不区分大小写的匹配"><a href="#不区分大小写的匹配" class="headerlink" title="不区分大小写的匹配"></a>不区分大小写的匹配</h3><p>通常，正则表达式是不区分大小写的，但是有时候，你不关心他们是不是大小写，可以向 re.compile() 传入re.IGNORECASE 或 re.I, 作为第二个参数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    robocop = re.compile(<span class="string">r'wanghao'</span>,re.I)</span><br><span class="line">    print(robocop.search(<span class="string">'WangHao is my best friends.'</span>).group())</span><br><span class="line">    <span class="comment"># WangHao</span></span><br><span class="line"></span><br><span class="line">    print(robocop.search(<span class="string">'WANGHAO is my best friends.'</span>).group())</span><br><span class="line">    <span class="comment"># WANGHAO</span></span><br><span class="line"></span><br><span class="line">    print(robocop.search(<span class="string">'wanghao is my best friends.'</span>).group())</span><br><span class="line">    <span class="comment"># wanghao</span></span><br></pre></td></tr></table></figure>
<h3 id="用sub-方法替换字符串"><a href="#用sub-方法替换字符串" class="headerlink" title="用sub()方法替换字符串"></a>用sub()方法替换字符串</h3><ul>
<li>正则表达式不仅能够找到这些匹配的文本，而且还可以用新的文本替换掉这些模式，那就是 sub() 方法 这个方法接受两个参数，第一个是用于取代发现的匹配，第二个是正则表达式匹配的内容</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    namesRegex = re.compile(<span class="string">r'Wang \w+'</span>)</span><br><span class="line">    mo = namesRegex.sub(<span class="string">'CENSORED'</span>,<span class="string">'Wang hao gives the ben to Wang Tao'</span>)</span><br><span class="line">    print(mo)</span><br><span class="line">    <span class="comment"># CENSORED gives the ben to CENSORED</span></span><br></pre></td></tr></table></figure>
<ul>
<li><p>有时候，你可能需要使用匹配的文本本身，作为替换的一部分，sub() 第一个参数的 \1、\2、\3 ……,表示‘在替换中输入分组1、2、3……的文本’</p>
</li>
<li><p>例如加入要隐去密探的姓名，只显示他们名字的第一个字母， 就可以使用正则表达式 Wang(\w)\w* ,传入 ‘r\1<em>**</em>‘ 作为sub() 的第一个参数，字符串中的\1 将由分组 1 匹配的文本所替代</p>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    agentNamesRegex = re.compile(<span class="string">r'Wang (\w)\w*'</span>)</span><br><span class="line">    mo = agentNamesRegex.sub(<span class="string">r'\1***'</span>,<span class="string">'Wang hao gives Wang tianrui to Wang tao.'</span>)</span><br><span class="line">    print(mo)</span><br><span class="line">    <span class="comment"># h*** gives t*** to t***.</span></span><br></pre></td></tr></table></figure>
<h3 id="管理复杂的正则表达式"><a href="#管理复杂的正则表达式" class="headerlink" title="管理复杂的正则表达式"></a>管理复杂的正则表达式</h3><ul>
<li>匹配简单的文本模式，正则表达式还应付过来，但是要匹配复杂的文本模式，可能会有点棘手，不过，你可以告诉 re.compile() ,忽略正则表达式字符串中的空白符和注释，从而缓解这一点，要想实现这一模式，可以向re.compile() 传入变量 re.VERBOSE,作为第二个参数</li>
<li>摈弃了之前的这种啰嗦</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    phoneRegex = re.compile(<span class="string">r'(((\d&#123;3&#125;|\(\d&#123;3&#125;\)))?(\s|-|\.)?\d&#123;3&#125;(\s|-|\.)\d&#123;4&#125;(\s*(ext|x|ext.)\s*\d&#123;2,5&#125;)?)'</span>)</span><br></pre></td></tr></table></figure>
<ul>
<li>改进之后的表达式</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    phoneRegex = re.compile(<span class="string">r'''(</span></span><br><span class="line"><span class="string">        ((\d&#123;3&#125;|\(\d&#123;3&#125;\)))?  # 电话地区号</span></span><br><span class="line"><span class="string">        (\s|-|\.)?    # 分隔符</span></span><br><span class="line"><span class="string">        \d&#123;3&#125;    # 前3位数字</span></span><br><span class="line"><span class="string">        (\s|-|\.)   # 分隔符</span></span><br><span class="line"><span class="string">        \d&#123;4&#125;   # 后四位数字</span></span><br><span class="line"><span class="string">        (\s*(ext|x|ext.)\s*\d&#123;2,5&#125;)?   # 拓展</span></span><br><span class="line"><span class="string">        )'''</span>,re.VERBOSE)</span><br></pre></td></tr></table></figure>
<h3 id="组合使用-re-IGNORECASE、re-DOTALL-和-re-VERBOSE"><a href="#组合使用-re-IGNORECASE、re-DOTALL-和-re-VERBOSE" class="headerlink" title="组合使用 re.IGNORECASE、re.DOTALL 和 re.VERBOSE"></a>组合使用 re.IGNORECASE、re.DOTALL 和 re.VERBOSE</h3><p>如果你想用 re.VERBOSE 来鞭子额注释，又想用 re.IGNORECASE 来忽略大小写，抱歉，re.compile 函数只接受一个只作为它的第二个参数，不过我们可以使用管道来跳过这个限制，即用 | 将两个参数分隔开</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">someRegex = re.compile(<span class="string">'foo'</span> ,re.IGNORECASE | re.UNICODE)</span><br></pre></td></tr></table></figure>
<h2 id="电话号码和-E-mail-地址提取程序"><a href="#电话号码和-E-mail-地址提取程序" class="headerlink" title="电话号码和 E-mail 地址提取程序"></a>电话号码和 E-mail 地址提取程序</h2><h3 id="先为电话号码创建一个正则表达式"><a href="#先为电话号码创建一个正则表达式" class="headerlink" title="先为电话号码创建一个正则表达式"></a>先为电话号码创建一个正则表达式</h3><p>首先需要创建一个正则表达式才能够用来查找电话号码</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re,pyperclip</span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    phoneRegex = re.compile(<span class="string">r'''(</span></span><br><span class="line"><span class="string">        (\d&#123;3&#125;|\(\d&#123;3&#125;\))?  # 电话地区号 三个数字(即\d&#123;3&#125;) 或括号里面三个数字(即 \(\d&#123;3&#125;\) )</span></span><br><span class="line"><span class="string">        (\s|-|\.)?    # 分隔符  空格(\s)、短横(-) 或 句点 (.)</span></span><br><span class="line"><span class="string">        \d&#123;3&#125;    # 前3位数字</span></span><br><span class="line"><span class="string">        (\s|-|\.)   # 分隔符</span></span><br><span class="line"><span class="string">        \d&#123;4&#125;   # 后四位数字</span></span><br><span class="line"><span class="string">        (\s*(ext|x|ext.)\s*\d&#123;2,5&#125;)?   # 拓展</span></span><br><span class="line"><span class="string">        )'''</span>,re.VERBOSE)</span><br></pre></td></tr></table></figure>
<h3 id="为-E-mail-地址创建一个正则表达式"><a href="#为-E-mail-地址创建一个正则表达式" class="headerlink" title="为 E-mail 地址创建一个正则表达式"></a>为 E-mail 地址创建一个正则表达式</h3><ul>
<li>用户名可以是一个或多个字符串，大小写字母、数字、句点、下划线、百分号、加号或短横</li>
<li>域名跟姓名用 @ 分隔开</li>
<li>姓名 可以是大小写字母、数字、句号跟下划线</li>
<li>.com 部分 其实可以匹配 .三个字母</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">emailRegex = re.compile(<span class="string">r'''</span></span><br><span class="line"><span class="string">        [a-zA-Z0-9._%+-]+  # username</span></span><br><span class="line"><span class="string">        @               # @符号</span></span><br><span class="line"><span class="string">        [a-zA-Z0-9._]+  # 姓名</span></span><br><span class="line"><span class="string">        (\.[a-zA-Z]&#123;2,4&#125;)  # . 跟其他的一些东西</span></span><br><span class="line"><span class="string">        '''</span>,re.VERBOSE)</span><br></pre></td></tr></table></figure>
<h3 id="在剪切板文本中找到所有匹配"><a href="#在剪切板文本中找到所有匹配" class="headerlink" title="在剪切板文本中找到所有匹配"></a>在剪切板文本中找到所有匹配</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">text = str(pyperclip.paste())</span><br><span class="line">   matches = []</span><br><span class="line">   <span class="comment"># 查找 电话号码</span></span><br><span class="line">   <span class="keyword">for</span> groups <span class="keyword">in</span> phoneRegex.findall(text):</span><br><span class="line">       <span class="comment">#  1、3、5 正好是 区号、前三个跟后四个数字</span></span><br><span class="line">       phoneNum = <span class="string">'_'</span>.join([groups[<span class="number">1</span>],groups[<span class="number">3</span>],groups[<span class="number">5</span>]])</span><br><span class="line">       <span class="keyword">if</span> groups[<span class="number">8</span>] != <span class="string">''</span>:</span><br><span class="line">           phoneNum += <span class="string">' x'</span> + groups[<span class="number">8</span>]</span><br><span class="line">       matches.append(phoneNum)</span><br><span class="line">   <span class="comment"># 查找 电子邮件</span></span><br><span class="line">   <span class="keyword">for</span> groups <span class="keyword">in</span> emailRegex.findall(text):</span><br><span class="line">       matches.append(groups[<span class="number">0</span>])</span><br></pre></td></tr></table></figure>
<h3 id="所有匹配连接成一个字符串，赋值到剪切板"><a href="#所有匹配连接成一个字符串，赋值到剪切板" class="headerlink" title="所有匹配连接成一个字符串，赋值到剪切板"></a>所有匹配连接成一个字符串，赋值到剪切板</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> len(matches) &gt; <span class="number">0</span>:</span><br><span class="line">       pyperclip.copy(<span class="string">'\n'</span>.join(matches))</span><br><span class="line">       print(<span class="string">'Copied to clipboard:'</span>)</span><br><span class="line">       print(<span class="string">'\n'</span>.join(matches))</span><br><span class="line">   <span class="keyword">else</span>:</span><br><span class="line">       print(<span class="string">'No phone numbers or emial address found.'</span>)</span><br></pre></td></tr></table></figure>
<h3 id="运行程序"><a href="#运行程序" class="headerlink" title="运行程序"></a>运行程序</h3><p>打开浏览器，访问　<a href="https://nostarch.com/contactus" target="_blank" rel="noopener">https://nostarch.com/contactus</a>　,将页面当中的所有数据赋值到剪切板，打开程序，运行</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re,pyperclip</span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    <span class="comment"># 电话号码的正则表达式</span></span><br><span class="line">    phoneRegex = re.compile(<span class="string">r'''(</span></span><br><span class="line"><span class="string">        (\d&#123;3&#125;|\(\d&#123;3&#125;\))?  # 电话地区号</span></span><br><span class="line"><span class="string">        (\s|-|\.)?    # 分隔符</span></span><br><span class="line"><span class="string">        (\d&#123;3&#125;)    # 前3位数字</span></span><br><span class="line"><span class="string">        (\s|-|\.)   # 分隔符</span></span><br><span class="line"><span class="string">        (\d&#123;4&#125;)   # 后四位数字</span></span><br><span class="line"><span class="string">        (\s*(ext|x|ext\.)\s*(\d&#123;2,5&#125;))?   # 拓展</span></span><br><span class="line"><span class="string">        )'''</span>,re.VERBOSE)</span><br><span class="line">    <span class="comment"># E-mial 的正则表达式</span></span><br><span class="line">    emailRegex = re.compile(<span class="string">r'''(</span></span><br><span class="line"><span class="string">        [a-zA-Z0-9._%+-]+  # username</span></span><br><span class="line"><span class="string">        @               # @符号</span></span><br><span class="line"><span class="string">        [a-zA-Z0-9.-]+  # 姓名</span></span><br><span class="line"><span class="string">        (\.[a-zA-Z]&#123;2,4&#125;)  # . 跟其他的一些东西</span></span><br><span class="line"><span class="string">        )'''</span>,re.VERBOSE)</span><br><span class="line">    text = str(pyperclip.paste())</span><br><span class="line">    matches = []</span><br><span class="line">    <span class="comment"># 查找 电话号码</span></span><br><span class="line">    <span class="keyword">for</span> groups <span class="keyword">in</span> phoneRegex.findall(text):</span><br><span class="line">        <span class="comment">#  1、3、5 正好是 区号、前三个跟后四个数字</span></span><br><span class="line">        phoneNum = <span class="string">'-'</span>.join([groups[<span class="number">1</span>],groups[<span class="number">3</span>],groups[<span class="number">5</span>]])</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> groups[<span class="number">8</span>] != <span class="string">''</span>:</span><br><span class="line">            phoneNum += <span class="string">' x'</span> + groups[<span class="number">8</span>]</span><br><span class="line">        matches.append(phoneNum)</span><br><span class="line">    <span class="comment"># 查找 电子邮件</span></span><br><span class="line">    <span class="keyword">for</span> groups <span class="keyword">in</span> emailRegex.findall(text):</span><br><span class="line">        matches.append(groups[<span class="number">0</span>])</span><br><span class="line">    <span class="keyword">if</span> len(matches) &gt; <span class="number">0</span>:</span><br><span class="line">        pyperclip.copy(<span class="string">'\n'</span>.join(matches))</span><br><span class="line">        print(<span class="string">'Copied to clipboard:'</span>)</span><br><span class="line">        print(<span class="string">'\n'</span>.join(matches))</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        print(<span class="string">'No phone numbers or emial address found.'</span>)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 结果：</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    Copied to clipboard:</span></span><br><span class="line"><span class="string">    800-420-7240</span></span><br><span class="line"><span class="string">    415-863-9900</span></span><br><span class="line"><span class="string">    415-863-9950</span></span><br><span class="line"><span class="string">    info@nostarch.com</span></span><br><span class="line"><span class="string">    media@nostarch.com</span></span><br><span class="line"><span class="string">    academic@nostarch.com</span></span><br><span class="line"><span class="string">    info@nostarch.com</span></span><br><span class="line"><span class="string">    '''</span></span><br></pre></td></tr></table></figure>
<hr>
<p>具体代码：Github Pages:  　<a href="https://github.com/wanghao15536870732/Quick-Python-Programming/blob/master/automate_online_materials/phoneAndEmail.py" target="_blank" rel="noopener">hyyyrwang.github.io</a></p>

      
    </div>
    
    
    

    

    

    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"><i class="fa fa-tag"></i> Python</a>
          
            <a href="/tags/Python编程快速上手/" rel="tag"><i class="fa fa-tag"></i> Python编程快速上手</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/09/02/python/python_note_1/" rel="next" title="Python编程快速上手 学习笔记(一) 匹配模式与正则表达式">
                <i class="fa fa-chevron-left"></i> Python编程快速上手 学习笔记(一) 匹配模式与正则表达式
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/09/08/python/python_note_3/" rel="prev" title="Python编程快速上手 学习笔记(三) 从Web抓取信息">
                Python编程快速上手 学习笔记(三) 从Web抓取信息 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zOTQxMi8xNTkzOQ=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/uploads/icon.jpg"
                alt="HyYyr Wang" />
            
              <p class="site-author-name" itemprop="name">HyYyr Wang</p>
              <p class="site-description motion-element" itemprop="description">我不是程序员，也不是设计师，只是喜欢编程，热爱python，碰巧有一些想法跟一台电脑</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">24</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/wanghao15536870732" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:hyyyrwang@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.douban.com/people/183791128" target="_blank" title="豆瓣">
                      
                        <i class="fa fa-fw fa-globe"></i>豆瓣</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/be-forever-82/activities" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-globe"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/964bc0f1e88e" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-globe"></i>简书</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_41005535" target="_blank" title="CSND">
                      
                        <i class="fa fa-fw fa-globe"></i>CSND</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                推荐阅读
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="npm install hexo-wordcount --save" title="秋冬夜漫长" target="_blank">秋冬夜漫长</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://angus-liu.github.io" title="Angus-Liu" target="_blank">Angus-Liu</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://innofang.github.io" title="Inno Fang" target="_blank">Inno Fang</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://barackbao.com" title="Barack Bao" target="_blank">Barack Bao</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://wmpscc.github.io" title="wmpscc" target="_blank">wmpscc</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://kentanvictor.github.io" title="JohnnyTan" target="_blank">JohnnyTan</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://xmmmmmovo.github.io/" title="xmmmmmovo Zha" target="_blank">xmmmmmovo Zha</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Python编程快速上手-学习笔记-二"><span class="nav-number">1.</span> <span class="nav-text">Python编程快速上手 学习笔记(二)</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#先复习一下上一篇文章Python编程快速上手-学习笔记-一-匹配模式与正则表达式-的主要内容"><span class="nav-number">1.1.</span> <span class="nav-text">先复习一下上一篇文章Python编程快速上手 学习笔记(一) 匹配模式与正则表达式 的主要内容</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#深入学习正则表达式"><span class="nav-number">1.2.</span> <span class="nav-text">深入学习正则表达式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#不区分大小写的匹配"><span class="nav-number">1.2.1.</span> <span class="nav-text">不区分大小写的匹配</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#用sub-方法替换字符串"><span class="nav-number">1.2.2.</span> <span class="nav-text">用sub()方法替换字符串</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#管理复杂的正则表达式"><span class="nav-number">1.2.3.</span> <span class="nav-text">管理复杂的正则表达式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#组合使用-re-IGNORECASE、re-DOTALL-和-re-VERBOSE"><span class="nav-number">1.2.4.</span> <span class="nav-text">组合使用 re.IGNORECASE、re.DOTALL 和 re.VERBOSE</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#电话号码和-E-mail-地址提取程序"><span class="nav-number">1.3.</span> <span class="nav-text">电话号码和 E-mail 地址提取程序</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#先为电话号码创建一个正则表达式"><span class="nav-number">1.3.1.</span> <span class="nav-text">先为电话号码创建一个正则表达式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#为-E-mail-地址创建一个正则表达式"><span class="nav-number">1.3.2.</span> <span class="nav-text">为 E-mail 地址创建一个正则表达式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#在剪切板文本中找到所有匹配"><span class="nav-number">1.3.3.</span> <span class="nav-text">在剪切板文本中找到所有匹配</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#所有匹配连接成一个字符串，赋值到剪切板"><span class="nav-number">1.3.4.</span> <span class="nav-text">所有匹配连接成一个字符串，赋值到剪切板</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#运行程序"><span class="nav-number">1.3.5.</span> <span class="nav-text">运行程序</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HyYyr Wang</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>


<div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span> </span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有 <span id="busuanzi_value_site_uv"></span> 人看过我的博客啦
</span>
</div>





<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共33.8k字</span>
</div>

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
